package com.qianchang.microfinance.view.mine.bill;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.OneLineLinearLayout;
import com.dm.library.widgets.element.DButton;
import com.dm.library.widgets.element.DTextView;
import com.dm.library.widgets.statusbar.StatusBarUtil;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.MyBillBean;
import com.qianchang.microfinance.bean.RepayDetailBean;
import com.qianchang.microfinance.bean.RepayPlanAfterParams;
import com.qianchang.microfinance.bean.ShowBillDetailMsgBean;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.utils.RepayModeUtil;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.mine.loan.LoanAgreementActivity;
import com.qianchang.microfinance.view.mine.loan.RepayPlanActivity;
import com.qianchang.microfinance.view.mine.loan.RepaymentRecordActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MyBillDetailActivity extends BaseActivity {

    private static final String TAG = "MyBillDetailActivity";
    @BindView(R.id.tv_total)
    DTextView tvTotal;
    @BindView(R.id.tv_period)
    DTextView tvPeriod;
    @BindView(R.id.tv_Principal)
    DTextView tvPrincipal;
    @BindView(R.id.tv_interest)
    DTextView tvInterest;
    @BindView(R.id.tv_overdue)
    DTextView tvOverDue;
    @BindView(R.id.tv_repay_mode)
    DTextView tvRepayMode;
    @BindView(R.id.tv_repay_date)
    DTextView tvRepayDate;
    @BindView(R.id.oll_repay_plan)
    OneLineLinearLayout ollRepayPlan;
    @BindView(R.id.oll_repay_record)
    OneLineLinearLayout ollRepayRecord;
    @BindView(R.id.oll_loan_agreement)
    OneLineLinearLayout ollLoanAgreement;
    @BindView(R.id.btn_repay)
    DButton btnRepay;
    @BindView(R.id.ll_msg)
    LinearLayout llMsg;
    private MyBillBean.Bean bean;
    private String repaymentTypeId;//还款方式id

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_bill_detail);
        StatusBarUtil.setTranslucentForImageViewInFragment(MyBillDetailActivity.this, null);
        ButterKnife.bind(this);
        setTitleName(getString(R.string.Title_Repay_Detail));
        initListener();
        initData();
        ifShowMsg();
    }

    private void ifShowMsg() {
        show();
        HttpParams params = new HttpParams();
        params.put("singleConfigType", "IS_AUTOMATIC_REPAYMENT"); //产品Id项目id
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.IF_SHOW_MY_BILL_DETAIL_MSG, params, new RequestCallBack<List<ShowBillDetailMsgBean>>() {
            @Override
            public void onSuccess(JsonResult<List<ShowBillDetailMsgBean>> response) {
                dismiss();
                Log.i(TAG, response.toString());
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    List<ShowBillDetailMsgBean> list = response.getObject();
                    if (list != null && !list.isEmpty()) {
                        if (list.get(0).isValue()) {
                            llMsg.setVisibility(View.VISIBLE);
                        } else {
                            llMsg.setVisibility(View.GONE);
                        }
                    } else {
                        llMsg.setVisibility(View.GONE);
                    }
                } else {
                    llMsg.setVisibility(View.GONE);
                    ToastUtil.getInstant().show(MyBillDetailActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(MyBillDetailActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                ToastUtil.getInstant().show(MyBillDetailActivity.this, msg);
            }
        });
    }

    private void initListener() {
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getBundle();
        if (bundle != null) {
            bean = (MyBillBean.Bean) bundle.getSerializable(MyBillAdapter.ENTITY_KEY);
            getDetail();
        } else {
            bean = new MyBillBean.Bean();
            ToastUtil.getInstant().show(this, getString(R.string.data_error));
        }
    }

    private void getDetail() {
        show();
        HttpParams params = new HttpParams();
        params.put("projectId", bean.getProjectId()); //产品Id项目id
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.REPAY_DETAIL, params, new RequestCallBack<RepayDetailBean>() {
            @Override
            public void onSuccess(JsonResult<RepayDetailBean> response) {
                dismiss();
                Log.i(TAG, response.toString());
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    refreshView(response.getObject());
                } else {
                    ToastUtil.getInstant().show(MyBillDetailActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(MyBillDetailActivity.this, msg);// getString(R.string.msg_indentity_code_send_fail));
            }

            @Override
            public void onConnectFailure(String msg) {
                ToastUtil.getInstant().show(MyBillDetailActivity.this, msg);
            }
        });
    }

    private void refreshView(RepayDetailBean bean) {
        if (bean == null) return;
        repaymentTypeId = bean.getRepaymentType();
        tvTotal.setText(FormatUtil.numKbPointFormat(bean.getPrincipal() + bean.getInterest() + bean.getOverdue()));
        tvPeriod.setText(bean.getPeriod() + "/" + bean.getDeadline());
        tvPrincipal.setText(FormatUtil.numKbPointFormat(bean.getPrincipal()));
        tvInterest.setText(FormatUtil.numKbPointFormat(bean.getInterest()));
        tvOverDue.setText(FormatUtil.numKbPointFormat(bean.getOverdue()));
        tvRepayMode.setText(RepayModeUtil.getRepayMode(repaymentTypeId, this));
        tvRepayDate.setText(bean.getNextPayDate());
        if (this.bean.getOverdueDays() < 0) {//提前还款
            btnRepay.setText(getString(R.string.btn_repay_pre));
        } else if (this.bean.getOverdueDays() >= 0) {//立即还款
            btnRepay.setText(getString(R.string.btn_repay_now));
        }

    }

    @OnClick({R.id.oll_repay_plan, R.id.oll_repay_record, R.id.oll_loan_agreement, R.id.btn_repay})
    public void onViewClicked(View view) {
        //还款记录时间：realPayDate	String	还款时间（格式化之后）
        //还款计划时间：shouldPayDate	String	应还时间(格式化之后)
        switch (view.getId()) {
            case R.id.oll_repay_plan://还款计划
                Bundle bundle = getBundle();
                RepayPlanAfterParams params = new RepayPlanAfterParams();
                params.setMonthInterestRate(bean.getServiceFeeRate());
                params.setProjectId(bean.getProjectId());
                params.setRepayModeId(repaymentTypeId);
                bundle.putSerializable(RepayPlanAfterParams.class.getName(), params);
                bundle.putDouble("applyAmount", bean.getLoanAmount()); //借款金额
//                bundle.putString("repaymentType", bean.getProductType());// //还款方式
//sdf
                startActivity(RepayPlanActivity.class, bundle); //测试使用z占时注释

                break;
            case R.id.oll_repay_record://还款记录
                Bundle bundle_record = new Bundle();
                bundle_record.putString(ConstantAppInfo.PROJECT_ID, bean.getProjectId());
                startActivity(RepaymentRecordActivity.class, bundle_record);
                break;
            case R.id.oll_loan_agreement://借款合同
                Bundle bundle_agreement = new Bundle();
//                bundle_agreement.putString(ConstantAppInfo.AGREEMENT_ID, "0");
                bundle_agreement.putString(ConstantAppInfo.PROJECT_ID, bean.getProjectId());
                bundle_agreement.putString(ConstantAppInfo.PROJECT_TYPE, bean.getProductType());
                startActivity(LoanAgreementActivity.class, bundle_agreement);
                break;
            case R.id.btn_repay://立即还款
                if (bean.getOverdueDays() < 0) {
                    startActivity(PrePayBackActivity.class, getBundle());//提前还款 //
                } else {
                    startActivity(PayBackActivity.class, getBundle());//立即还款/逾期还款
                }
                break;
        }
    }
}
